package com.jsonal.service.impl.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jsonal.common.CommonUtil;
import com.jsonal.common.JsonUtils;
import com.jsonal.common.Md5Util;
import com.jsonal.entity.api.User;
import com.jsonal.entity.manager.LoginBean;
import com.jsonal.mapper.api.UserMapper;
import com.jsonal.service.manager.LoginService;
import com.jsonal.util.RedisUtil;
import com.jsonal.vo.Result;
import java.util.Objects;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: jingji.lin
 * @Description:
 * @Date: 2020/6/14 7:40
 * @Version: 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserMapper userMapper;

    /**
     * 管理员登录
     *
     * @param loginBean 用户名密码
     * @return res
     */
    @Override
    public Result login(LoginBean loginBean) {
        Result result = new Result();
        LoginBean bean = new LoginBean();
        User user = null;
        // 判断用户名密码不为空
        if (loginBean.getUsername() != null && loginBean.getPassword() != null) {
            // 判断缓存是否存在key
            if (!redisUtil.hasKey(loginBean.getUsername())) {
                user = userMapper
                    .selectOne(new QueryWrapper<User>().eq("username", loginBean.getUsername()));
                if (!Objects
                    .equals(Md5Util.passwordMd5(loginBean.getPassword()), user.getPassword())) {
                    return new Result(false, "密码不正确");
                }
            } else {
                user = JsonUtils.jsonToPojo(redisUtil.get(loginBean.getUsername()).toString(), User.class);
                if (!user.getPassword().equals(Md5Util.passwordMd5(loginBean.getPassword()))) {
                    return new Result(false, "密码不正确");
                }
            }
            if (user.getState()) {
                String token = user.getUsername() + "_" + CommonUtil.getGUID() + new Random().nextInt(1000);
                redisUtil.set(token, String.valueOf(System.currentTimeMillis()), 60*30);
                bean.setToken(token);
                result.setObj(bean);
                result.setSuccess(true);
                result.setMsg("登录成功");
                return result;
            } else {
                return new Result(false, "没有管理员权限");
            }
        }
        return new Result(false, "用户名或者密码不能为空");
    }
}
